package com.wzs.rpc.serializer;

import com.wzs.rpc.constant.RpcConstant;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

@Slf4j
public class SerializerFactory {
    private static final Map<String, Object> instanceCache = new HashMap<>();
    private static final Serializer DEFAULT_SERIALIZER = new JDKSerializer();

    //饿汉，加载时便初始化，避免多线程下的安全问题
    static {
        ServiceLoader<Serializer> serializers = ServiceLoader.load(Serializer.class);
        for (Serializer serializer : serializers) {
            instanceCache.put(serializer.getClass().getName(), serializer);
        }
        log.debug("SPI加载Serializer, 实例个数为 {}", instanceCache.size());
    }

    //serializer: 序列化器的全类名
    public static Serializer getInstance(String serializer) {
        return (Serializer) instanceCache.getOrDefault(serializer, DEFAULT_SERIALIZER);
    }
}
